//
//  IntegralViewController.m
//  Housekeeping
//
//  Created by 辰领科技 on 16/5/30.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "IntegralViewController.h"
#import "IntegralTableViewCell.h"


static NSString *CellIdentifier =@"IntegralTableViewCell";

@interface IntegralViewController ()
<UITableViewDelegate,UITableViewDataSource>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;



@property (strong, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UIScrollView *scroView;
@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) IBOutlet UIImageView *headPortraitImage;
@property (strong, nonatomic) IBOutlet UILabel *userNameLabel;
@property (strong, nonatomic) IBOutlet UILabel *integralLabel;

@property (strong, nonatomic)  NSString *integralString;
@property (strong, nonatomic)  NSMutableArray *commodityArray;

@end

@implementation IntegralViewController

- (void)viewWillAppear:(BOOL)animated{
    [self.scroView.header beginRefreshing];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _pageNO = 1;
    _commodityArray = [NSMutableArray array];
    [self initViewLayout];
    [self addRefreshing];
    [self getIntegral];
    
}

- (void)initViewLayout {
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    [self adaptiveViewLayout:self.scroView];
    
    _scroView.frame = CGRectMake(0, 64* VerticalRatio(), 320* VerticalRatio(), 504* VerticalRatio()-49);
    _scroView.contentSize = flexibleSize(CGSizeMake(0, 504* VerticalRatio()-48), NO);
    
    [self.tableView registerNib:[UINib nibWithNibName:CellIdentifier bundle:nil] forCellReuseIdentifier:CellIdentifier];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.userNameLabel.text = (NSString *)[Common getLoginInfo][Key_User_nickname];
    _headPortraitImage.layer.masksToBounds = YES;
    _headPortraitImage.layer.cornerRadius = 23.5*VerticalRatio();
    [_headPortraitImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,_headImage]]];
}


#pragma mark - <UITableViewDelegate && UITableViewDataSource>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
//定义 UITableView cell 的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.commodityArray.count;
}

//定义 UITableView cell 的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 55*VerticalRatio();
}

//定义 UITableView cell 展示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    IntegralTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {
        cell = [[IntegralTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    cell.commodityNameLabel.text = (NSString *)self.commodityArray[indexPath.row][@"migoName"];
    cell.needIntegralLabel.text = (NSString *)self.commodityArray[indexPath.row][@"migoNeedIntegration"];
    NSString * image = [NSString stringWithFormat:@"%@",self.commodityArray[indexPath.row][@"migoImage"]];
    if (image && image.length>0) {
        [cell.commodityImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,image]]];
    }
    
    cell.choseCell = ^(){
        NSMutableDictionary * dic = [NSMutableDictionary dictionary];
        [dic setObject:self.commodityArray[indexPath.row][@"migoId"] forKey:@"migoId"];
        [dic setObject:[Common getLoginInfo][Key_User_userId] forKey:@"museId"];
        [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
        [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
        [dic setObject:@"1" forKey:@"count"];
        self.shareApi.delegate = self;
        [self.shareApi  requestOperationWithDic:dic withPath:HK_saveMallIntegrationGoods withHttpType:@"POST" withTag:HK_HK_saveMallIntegrationGoods];

    };
    
    return cell;
}


#pragma mark - 积分记录
- (IBAction)IntegralRecord:(id)sender {
    UIStoryboard *secondStroyBoard = [UIStoryboard storyboardWithName:@"PersonalStoryboard" bundle:nil];
    UIViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"IntegralRecord"];
    [[Common getNavigation]pushViewController:page];
}

#pragma mark - 返回
- (IBAction)back:(id)sender {
    [self backBtn];
}


#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.scroView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.scroView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getCommodityInfo];
        });
    }];

}
//加载更多数据
- (void)loadMoreData{
    if (self.commodityArray.count == _totle) {
        [self.scroView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getCommodityInfo];
        });
    }
    
}



#pragma mark - 积分兑换列表
- (void)getIntegral {
    if (![Common getLoginStatus]) {
        [[AppDelegate sharedAppDelegate]ShowLoginPage];
        return;
    }
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    [dic setObject:[Common getLoginInfo][Key_User_userId] forKey:@"museId"];
    [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
    [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
    
    self.shareApi.delegate = self;
    [self.shareApi  requestOperationWithDic:dic withPath:HK_queryMmemberScore withHttpType:@"POST" withTag:HK_HK_queryMmemberScore];
}

- (void)getCommodityInfo {
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    self.shareApi.delegate = self;
    [self.shareApi  requestOperationWithDic:dic withPath:HK_queryMallIntegrationGoods withHttpType:@"POST" withTag:HK_HK_queryMallIntegrationGoods];
}



#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    [_scroView.header endRefreshing];
    [_scroView.footer endRefreshing];
    if (tag == HK_HK_queryMmemberScore){
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
        }else  {
            self.integralString = database[@"result"][@"museSore"];
            
            self.integralLabel.text = [NSString stringWithFormat:@"积分：%@",self.integralString];
        }
    }
    
    if (tag == HK_HK_queryMallIntegrationGoods){
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
        }else  {
            dispatch_async(dispatch_get_main_queue(), ^{
                _totle = [database[@"result"][@"total"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.scroView.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.scroView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.commodityArray removeAllObjects];
                }
                NSArray *arr = database[@"result"][@"rows"];
                for (id entity in arr) {
                    [self.commodityArray addObject:entity];
                }
                _tableView.dataSource = self;
                _tableView.delegate = self;
                [_tableView reloadData];
                
            });
        }
    }
    
    if (tag == HK_HK_saveMallIntegrationGoods){
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
        }else  {

            [CWHUDTips showTips:@"兑换成功"];
        }
    }


}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
    [self dismissWaitDialog];
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

@end
